#include "graphwidget.h"

#include <QtGui>
#include <QtDebug>

#include <math.h>


GraphWidget::GraphWidget(QWidget *parent)
    : QGraphicsView(parent)
{
    QGraphicsScene *scene = new QGraphicsScene(this);
    scene->setItemIndexMethod(QGraphicsScene::NoIndex);
    setScene(scene);

    setCacheMode(CacheBackground);
    setViewportUpdateMode(BoundingRectViewportUpdate);
    setRenderHint(QPainter::Antialiasing);
    setTransformationAnchor(AnchorUnderMouse);
}

int GraphWidget::loadBoardPic(QString filename)
{
    QPixmap bg(filename);
    if ( bg.isNull() ) return -1;

    setSceneRect(bg.rect());

    // Fix la taille de la fenetre en fonction de la taille de l'image
    int pad = 10;
    setMinimumWidth(bg.size().width()+pad);
    setMinimumHeight(bg.size().height()+pad);
    setMaximumWidth(bg.size().width()+pad);
    setMaximumHeight(bg.size().height()+pad);

    //bg.scaled(size());
    this->scene()->addPixmap(bg);
    return 0;
}

void GraphWidget::mousePressEvent(QMouseEvent* ev)
{
    if ( ev->button() != Qt::LeftButton )
        return;

    QPoint point = ev->pos();

    qDebug()<< "<< " << point ;

}


void GraphWidget::itemMoved()
{

}


void GraphWidget::keyPressEvent(QKeyEvent *event)
{
    Q_UNUSED(event);
}


void GraphWidget::wheelEvent(QWheelEvent *event)
{
    scaleView(pow((double)2, -event->delta() / 240.0));
}

void GraphWidget::drawBackground(QPainter *painter, const QRectF &rect)
{
    Q_UNUSED(rect);
    Q_UNUSED(painter);
}

void GraphWidget::scaleView(qreal scaleFactor)
{
    qreal factor = transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width();
    if (factor < 0.07 || factor > 100)
        return;

    scale(scaleFactor, scaleFactor);
}

